package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.time.LocalDateTime;
import java.time.LocalTime;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private WeChatProperties weChatProperties;

    @Autowired
    private UserMapper userMapper;

    public static final String WXURL = "https://api.weixin.qq.com/sns/jscode2session";

    /**
     * 微信用户登录
     * @param userLoginDTO
     * @return
     */
    public User login(UserLoginDTO userLoginDTO) {
        log.info("微信登录:{}" + userLoginDTO.getCode());
        //通过restTemplate调用微信接口服务获取openid
        URI url = URI.create(WXURL + "?appid=" + weChatProperties.getAppid() + "&secret=" + weChatProperties.getSecret() + "&js_code=" + userLoginDTO.getCode() + "&grant_type=authorization_code");
        String data = restTemplate.getForObject(url, String.class);
        // JSON字符串转换为JSON对象
        JSONObject jsonObject = JSON.parseObject(data);
        // 获取结果中的openid
        String openid = jsonObject.getString("openid");
        // 判断是否为空，为空代表失败，抛出异常
        if (openid == null) {
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        // 不为空，根据openid查询数据库，如果数据库中没有该用户，就插入一条新的用户记录
        User user = userMapper.selectByOpenid(openid);
        if (user == null) {
            user = user.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.insert(user);
        }

        // 返回用户信息
        return user;
    }
}
